/**
 * 封装本地存储
 *
 * @param key 存储名字
 * @param value 存储值
 */
export const local = {
  //存储
  set(key: string, value: any) {
    localStorage.setItem(key, btoa(escape(JSON.stringify(value))));
  },
  //取出数据
  get<T>(key: string) {
    const value = localStorage.getItem(key);
    if (value && value != "undefined" && value != "null") {
      return <T>JSON.parse(unescape(atob(value)));
    }
  },
  // 删除数据
  remove(key: string) {
    localStorage.removeItem(key);
  },
  // 清空本地数据
  clear() {
    localStorage.clear();
  },
};

/**
 * 封装操作sessionStorage本地存储的方法
 * @param key 存储名字
 * @param value 存储值
 */
export const session = {
  //存储
  set(key: string, value: any) {
    window.sessionStorage.setItem(key, btoa(escape(JSON.stringify(value))));
  },
  //取出数据
  get<T>(key: string) {
    const value = window.sessionStorage.getItem(key);
    if (value && value != "undefined" && value != "null") {
      return JSON.parse(unescape(atob(value)));
    }
    return null;
  },
  // 删除数据
  remove(key: string) {
    window.sessionStorage.removeItem(key);
  },
  clear() {
    localStorage.clear();
  },
};

/**
 * 封装操作cookie本地存储的方法
 * @param key 存储名字
 * @param value 存储值
 * @param day 数据过期时间
 */
export const cookie = {
  // 设置值
  set(key: string, val: any, day: any) {
    var date = new Date();
    date.setDate(date.getDate() + day);
    document.cookie =
      key + "=" + btoa(escape(JSON.stringify(val))) + ";expires=" + date;
  },
  //读取值
  get(key: string) {
    var reg = RegExp(key + "=([^;]+)");
    var arr = document.cookie.match(reg);
    if (arr) {
      return JSON.parse(unescape(atob(arr[1])));
    } else {
      return "";
    }
  },
  //删除值  原理是过去的日期对象
  remove(key: string) {
    cookie.set(key, null, -1);
  },
};
